import { Anthropic } from "@anthropic-ai/sdk"
import { ApiHandler, ApiHandlerMessageResponse } from "../"
import { ApiHandlerOptions, ModelInfo, openAiModelInfoSaneDefaults } from "../../shared/api"
import { convertToAnthropicMessage, convertToOpenAiMessages } from "../transform/openai-format"
import axios from 'axios'
import * as fs from 'fs';

export class OllamaHandler implements ApiHandler {
    private options: ApiHandlerOptions
    private baseURL: string

    constructor(options: ApiHandlerOptions) {
        this.options = options
        this.baseURL = (this.options.ollamaBaseUrl || "http://localhost:11434") + "/v1"
    }

    async createMessage(
        systemPrompt: string,
        messages: Anthropic.Messages.MessageParam[],
        tools: Anthropic.Messages.Tool[]
    ): Promise<ApiHandlerMessageResponse> {
        const openAiMessages: any[] = [
            { role: "system", content: systemPrompt },
            ...convertToOpenAiMessages(messages),
        ]
        const openAiTools: any[] = tools.map((tool) => ({
            type: "function",
            function: {
                name: tool.name,
                description: tool.description,
                parameters: tool.input_schema,
            },
        }))
        const createParams: any = {
            model: this.options.ollamaModelId ?? "",
            messages: openAiMessages,
            temperature: 0.2,
            tools: openAiTools,
            tool_choice: "auto",
            max_tokens: 32768,
        }

        try {
			const createParamsJson = JSON.stringify(createParams, null, 2);

			// 写入文件
			fs.appendFile('createParams.json', createParamsJson, (err) => {
				if (err) throw err;
				console.log('createParams is saved!');
			});
            const response = await axios.post(`${this.baseURL}/chat/completions`, createParams, {
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer ollama'
                }
            })

            const completion = response.data
            const anthropicMessage = convertToAnthropicMessage(completion)
            return { message: anthropicMessage }
        } catch (error) {
            if (axios.isAxiosError(error) && error.response) {
                throw new Error(error.response.data.error?.message || 'Unknown error occurred')
            }
            throw error
        }
    }

    getModel(): { id: string; info: ModelInfo } {
        return {
            id: this.options.ollamaModelId ?? "",
            info: openAiModelInfoSaneDefaults,
        }
    }
}